//
//  RxWebViewController.m
//  RxWebViewController
//
//  Created by roxasora on 15/10/23.
//  Copyright © 2015年 roxasora. All rights reserved.
//

#import "RxWebViewController.h"
#import "NJKWebViewProgress.h"
#import "NJKWebViewProgressView.h"
#import "WebViewJavascriptBridge.h"

#define boundsWidth self.view.bounds.size.width
#define boundsHeight self.view.bounds.size.height

#define MOVEDISTANCE 99                 // 左侧一开始的距离
#define VIEWALPHA 0.8                   // 初始化alpha数值
#define VIEWCOLOR [UIColor blackColor]  // 遮罩的颜色


typedef NS_ENUM(NSInteger, ViewType) {
    ShadowImgView  = 2,
    BlackAlphaView = 3,
};

@interface RxWebViewController ()<UIWebViewDelegate,UINavigationControllerDelegate,UINavigationBarDelegate,NJKWebViewProgressDelegate,UIGestureRecognizerDelegate>

@property (nonatomic)UIBarButtonItem* customBackBarItem;
@property (nonatomic)UIBarButtonItem* closeButtonItem;

@property (nonatomic)NJKWebViewProgress* progressProxy;
@property (nonatomic)NJKWebViewProgressView* progressView;

@property (nonatomic)WebViewJavascriptBridge *javascriptBridge;

/**
 *  array that hold snapshots
 */
@property (nonatomic)NSMutableArray* snapShotsArray;

/**
 *  current snapshotview displaying on screen when start swiping
 */
@property (nonatomic)UIView* currentSnapShotView;

/**
 *  previous view
 */
@property (nonatomic)UIView* prevSnapShotView;

/**
 *  background alpha black view
 */
@property (nonatomic)UIView* swipingBackgoundView;

/**
 *  left pan ges
 */
@property (nonatomic)UIPanGestureRecognizer* swipePanGesture;

/**
 *  if is swiping now
 */
@property (nonatomic)BOOL isSwipingBack;

@property (nonatomic, assign) id<SHWebJavaScriptBridgeDelegate>javascriptDelegate;

/**
 *  没有网络时的提示层
 */
@property (nonatomic, strong) UIView *noNetworkView;

@property (nonatomic, strong) id<UIGestureRecognizerDelegate> recognizerDelegate;



/// status
@property (nonatomic, assign) BOOL notNeedScreenShot;

/// screen shots
@property (nonatomic, strong) NSMutableArray *imgArray;
@property (nonatomic, strong) UIImage *backScreenshotsImg;
@property (nonatomic, strong) UIView *showView;

@end

@implementation RxWebViewController

@synthesize isModelView;
@synthesize javascriptBridge;
@synthesize jsSharedBlock;
@synthesize jsPageActionBlock;
//@synthesize javascriptDelegate;

-(UIStatusBarStyle) preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

#pragma mark - init
-(instancetype)initWithUrl:(NSURL *)url{
    self = [super init];
    if (self) {
        self.url = url;
        _progressViewColor = [UIColor colorWithRed:119.0/255 green:228.0/255 blue:115.0/255 alpha:1];
    }
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.title = @"";
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    self.javascriptBridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
    [self.javascriptBridge setWebViewDelegate:self.progressProxy];
    
    
    //__weak strongSelf = self
    
    //self.webView.delegate = self.progressProxy;
    [self.view addSubview:self.webView];
    
    
    [self.javascriptBridge  registerHandler:@"onShareAppMessage" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"onShareAppMessage called: %@", data);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self onSharedAppMessage:data];
            responseCallback(@"success");
        });
    }];
    
    [self.javascriptBridge registerHandler:@"onPageAction" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"onPageAction called: %@", data);
        //dispatch_async(dispatch_get_main_queue(), ^{
            [self onPageActionMessage:data];
            responseCallback(@"success");
        //});
    }];
    
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:self.url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    //[urlRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    
    [self.webView loadRequest:urlRequest];
    
    [self.navigationController.navigationBar addSubview:self.progressView];
    // 导航栏 shadowImage
    self.navigationController.navigationBar.shadowImage = nil;
    
    /// add SomeThing
    self.imgArray = [[NSMutableArray alloc] initWithCapacity:10];
    UIPanGestureRecognizer *pangesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(methodPanGesture:)];
    pangesture.delegate = self;
    [self.view addGestureRecognizer:pangesture];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.progressView.hidden = false;
    
    if (self.isModelView == false) {
         if (self.navigationController.viewControllers.count > 1) {
             //_recognizerDelegate = self.navigationController.interactivePopGestureRecognizer.delegate;
             //self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
         }
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (self.isModelView == false) {
        //self.navigationController.interactivePopGestureRecognizer.delegate = _recognizerDelegate;
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.progressView.hidden = true;
    //    [self.progressView removeFromSuperview];
    //    [self.progressView removeFromSuperview];
    //    self.webView.delegate = nil;
    
}


- (void)setJavascriptDelegate:(id<SHWebJavaScriptBridgeDelegate>)javascriptDelegate {
    if (_javascriptDelegate == nil) {
        _javascriptDelegate = javascriptDelegate;
    }
}

- (id<SHWebJavaScriptBridgeDelegate>)getJavascriptDelegate {
    return _javascriptDelegate;
}

- (void)onSharedAppMessage:(NSDictionary*)dicData {
    
    if (self.jsSharedBlock) {
        self.jsSharedBlock(dicData);
    }
    if (_javascriptDelegate) {
        [_javascriptDelegate SHWebJavaScriptBridgeSharedWidth:dicData];
    }
}

- (void)onPageActionMessage:(NSDictionary*)dicData {
    if (self.jsPageActionBlock) {
        self.jsPageActionBlock(dicData);
    }
    if (_javascriptDelegate) {
        [_javascriptDelegate SHWebJavaScriptBridgePageAction:dicData];
    }
}




#pragma mark - public funcs
-(void)reloadWebView{
    [self.webView reload];
}

#pragma mark - logic of push and pop snap shot views
-(void)pushCurrentSnapshotViewWithRequest:(NSURLRequest*)request{
//    NSLog(@"push with request %@",request);
    NSURLRequest* lastRequest = (NSURLRequest*)[[self.snapShotsArray lastObject] objectForKey:@"request"];
    //如果url是很奇怪的就不push
    if ([request.URL.absoluteString isEqualToString:@"about:blank"]) {
        return;
    }
    //如果url一样就不进行push
    if ([lastRequest.URL.absoluteString isEqualToString:request.URL.absoluteString]) {
        return;
    }
    
    UIView* currentSnapShotView = [self.webView snapshotViewAfterScreenUpdates:YES];
    [self.snapShotsArray addObject:
     @{
       @"request":request,
       @"snapShotView":currentSnapShotView
       }
     ];
}

-(void)startPopSnapshotView{
    if (self.isSwipingBack) {
        return;
    }
    if (!self.webView.canGoBack) {
        return;
    }
    self.isSwipingBack = YES;
    //create a center of scrren
    CGPoint center = CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2);
    
    self.currentSnapShotView = [self.webView snapshotViewAfterScreenUpdates:YES];
    
    //add shadows just like UINavigationController
    self.currentSnapShotView.layer.shadowColor = [UIColor blackColor].CGColor;
    self.currentSnapShotView.layer.shadowOffset = CGSizeMake(3, 3);
    self.currentSnapShotView.layer.shadowRadius = 5;
    self.currentSnapShotView.layer.shadowOpacity = 0.75;
    
    //move to center of screen
    self.currentSnapShotView.center = center;
    
    self.prevSnapShotView = (UIView*)[[self.snapShotsArray lastObject] objectForKey:@"snapShotView"];
    center.x -= 60;
    self.prevSnapShotView.center = center;
    self.prevSnapShotView.alpha = 1;
    self.view.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.prevSnapShotView];
    [self.view addSubview:self.swipingBackgoundView];
    [self.view addSubview:self.currentSnapShotView];
}

-(void)popSnapShotViewWithPanGestureDistance:(CGFloat)distance{
    if (!self.isSwipingBack) {
        return;
    }
    
    if (distance <= 0) {
        return;
    }
    
    CGPoint currentSnapshotViewCenter = CGPointMake(boundsWidth/2, boundsHeight/2);
    currentSnapshotViewCenter.x += distance;
    CGPoint prevSnapshotViewCenter = CGPointMake(boundsWidth/2, boundsHeight/2);
    prevSnapshotViewCenter.x -= (boundsWidth - distance)*60/boundsWidth;
//    NSLog(@"prev center x%f",prevSnapshotViewCenter.x);
    
    self.currentSnapShotView.center = currentSnapshotViewCenter;
    self.prevSnapShotView.center = prevSnapshotViewCenter;
    self.swipingBackgoundView.alpha = (boundsWidth - distance)/boundsWidth;
}

-(void)endPopSnapShotView{
    if (!self.isSwipingBack) {
        return;
    }
    
    //prevent the user touch for now
    self.view.userInteractionEnabled = NO;
    
    if (self.currentSnapShotView.center.x >= boundsWidth) {
        // pop success
        [UIView animateWithDuration:0.2 animations:^{
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            
            self.currentSnapShotView.center = CGPointMake(boundsWidth*3/2, boundsHeight/2);
            self.prevSnapShotView.center = CGPointMake(boundsWidth/2, boundsHeight/2);
            self.swipingBackgoundView.alpha = 0;
        }completion:^(BOOL finished) {
            [self.prevSnapShotView removeFromSuperview];
            [self.swipingBackgoundView removeFromSuperview];
            [self.currentSnapShotView removeFromSuperview];
            [self.webView goBack];
            [self.snapShotsArray removeLastObject];
            self.view.userInteractionEnabled = YES;
            
            self.isSwipingBack = NO;
        }];
    }else{
        //pop fail
        [UIView animateWithDuration:0.2 animations:^{
            [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
            
            self.currentSnapShotView.center = CGPointMake(boundsWidth/2, boundsHeight/2);
            self.prevSnapShotView.center = CGPointMake(boundsWidth/2-60, boundsHeight/2);
            self.prevSnapShotView.alpha = 1;
        }completion:^(BOOL finished) {
            [self.prevSnapShotView removeFromSuperview];
            [self.swipingBackgoundView removeFromSuperview];
            [self.currentSnapShotView removeFromSuperview];
            self.view.userInteractionEnabled = YES;
            
            self.isSwipingBack = NO;
        }];
    }
}

#pragma mark - update nav items

-(void)updateNavigationItems{
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                    target:nil action:nil];
    negativeSpacer.width = -8;
    if (self.webView.canGoBack) {
//        UIBarButtonItem *spaceButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//        spaceButtonItem.width = -6.5;
//        
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        [self.navigationItem setLeftBarButtonItems:@[negativeSpacer,self.customBackBarItem,self.closeButtonItem] animated:NO];
        
        //弃用customBackBarItem，使用原生backButtonItem
//        [self.navigationItem setLeftBarButtonItems:@[spaceButtonItem,self.customBackBarItem,self.closeButtonItem] animated:NO];
    }else{
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        [self.navigationItem setLeftBarButtonItems:@[negativeSpacer,self.customBackBarItem]];
    }
}

#pragma mark - events handler
-(void)swipePanGestureHandler:(UIPanGestureRecognizer*)panGesture{
    CGPoint translation = [panGesture translationInView:self.webView];
    CGPoint location = [panGesture locationInView:self.webView];
    //NSLog(@"pan x %f,pan y %f",translation.x,translation.y);
    
    if (panGesture.state == UIGestureRecognizerStateBegan) {
        if (location.x <= 50 && translation.x > 0) {  //开始动画
            [self startPopSnapshotView];
        }
    }else if (panGesture.state == UIGestureRecognizerStateCancelled || panGesture.state == UIGestureRecognizerStateEnded){
        [self endPopSnapShotView];
    }else if (panGesture.state == UIGestureRecognizerStateChanged){
        [self popSnapShotViewWithPanGestureDistance:translation.x];
    }
}

-(void)customBackItemClicked{
    if ([self.webView canGoBack]) {
        [self.imgArray removeLastObject];
        [self.webView goBack];
    }
    else {
        [self closeItemClicked];
    }
}

-(void)closeItemClicked{
    
    if (self.isModelView == true) {
        [self dismissViewControllerAnimated:false completion:^{
            
        }];
    } else {
        self.progressProxy.webViewProxyDelegate = nil;
        self.progressProxy.progressDelegate = nil;
        self.jsSharedBlock = nil;
        self.jsPageActionBlock = nil;
        [self.webView stopLoading];
        [self.imgArray removeAllObjects];
        self.imgArray = nil;
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}
//
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer  {
//    
//    if ([self.webView canGoBack]) {
//        return false;
//    }
//    return true;
//    
//}

#pragma mark - UIGestureRecognizerDelegate
/*
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    if ([self.webView canGoBack]) {
        return false;
    }
    return self.navigationController.childViewControllers.count > 1;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    if ([self.webView canGoBack]) {
        return false;
    }
    
    return self.navigationController.viewControllers.count > 1;
}*/

#pragma mark - webView delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//    NSLog(@"navigation type %d",navigationType);
    
    switch (navigationType) {
        case UIWebViewNavigationTypeLinkClicked: {
            //[self pushCurrentSnapshotViewWithRequest:request];
            UIImage *webScreenshotsImg = [self getScreenshot];
            [self.imgArray addObject:webScreenshotsImg];
            self.notNeedScreenShot = YES;
            break;
        }
        case UIWebViewNavigationTypeFormSubmitted: {
            //[self pushCurrentSnapshotViewWithRequest:request];
            UIImage *webScreenshotsImg = [self getScreenshot];
            [self.imgArray addObject:webScreenshotsImg];
            self.notNeedScreenShot = YES;
            break;
        }
        case UIWebViewNavigationTypeBackForward: {
            break;
        }
        case UIWebViewNavigationTypeReload: {
            break;
        }
        case UIWebViewNavigationTypeFormResubmitted: {
            break;
        }
        case UIWebViewNavigationTypeOther: {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self pushCurrentSnapshotViewWithRequest:request];
//            });
            UIImage *webScreenshotsImg = [self getScreenshot];
            [self.imgArray addObject:webScreenshotsImg];
            self.notNeedScreenShot = YES;
            break;
        }
        default: {
            break;
        }
    }
    
    //if (!self.progressProxy.isFinishLoad && !self.notNeedScreenShot && navigationType != UIWebViewNavigationTypeBackForward) {
        /// add image
//        UIImage *webScreenshotsImg = [self getScreenshot];
//        [self.imgArray addObject:webScreenshotsImg];
//        self.notNeedScreenShot = YES;
    //}
    
    [self updateNavigationItems];
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateNavigationItems];
    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (theTitle.length > 10) {
        theTitle = [[theTitle substringToIndex:9] stringByAppendingString:@"…"];
    }
    self.title = theTitle;
    NSLog(@"webViewDidFinishLoad");
    
    [self.noNetworkView removeFromSuperview];
    
    if (self.progressProxy.isFinishLoad) {
        self.notNeedScreenShot = NO;
    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    [self updateNavigationItems];
    
    NSLog(@"didFailLoadWithError:%@,code: %ld",error.localizedDescription,error.code);
    // 似乎已断开与互联网的连接
    if (error.code == -1009) {
        self.webView.hidden = true;
        if ([self.noNetworkView superview] == nil) {
            [self.view insertSubview:self.noNetworkView aboveSubview:self.webView];
            self.noNetworkView.center = self.view.center;
        }
    }
}




#pragma mark - NJProgress delegate

-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [self.progressView setProgress:progress animated:NO];
}


#pragma mark - setters and getters
-(void)setUrl:(NSURL *)url{
    _url = url;
}

-(void)setProgressViewColor:(UIColor *)progressViewColor{
    _progressViewColor = progressViewColor;
    self.progressView.progressColor = progressViewColor;
}

-(UIWebView*)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        _webView.delegate = (id)self;
        _webView.scalesPageToFit = YES;
        _webView.backgroundColor = [UIColor whiteColor];
//        _webView.paginationMode = UIWebPaginationModeRightToLeft;
        //[_webView addGestureRecognizer:self.swipePanGesture];
    }
    return _webView;
}

-(UIBarButtonItem*)customBackBarItem{
    if (!_customBackBarItem) {
        
        //icon_back
        
        // backItemImage backItemImage-hl
        UIImage* backItemImage = [[UIImage imageNamed:@"icon_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        UIImage* backItemHlImage = [[UIImage imageNamed:@"icon_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        
        UIButton* backButton = [[UIButton alloc] init];
        [backButton setTitle:@"返回" forState:UIControlStateNormal];
        [backButton setTitleColor:self.navigationController.navigationBar.tintColor forState:UIControlStateNormal];
        [backButton setTitleColor:[self.navigationController.navigationBar.tintColor colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];
        [backButton.titleLabel setFont:[UIFont systemFontOfSize:17]];
        [backButton setImage:backItemImage forState:UIControlStateNormal];
        [backButton setImage:backItemHlImage forState:UIControlStateHighlighted];
        [backButton sizeToFit];
        
        [backButton addTarget:self action:@selector(customBackItemClicked) forControlEvents:UIControlEventTouchUpInside];
        _customBackBarItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    }
    return _customBackBarItem;
}

-(UIBarButtonItem*)closeButtonItem{
    if (!_closeButtonItem) {
        _closeButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeItemClicked)];
    }
    return _closeButtonItem;
}

-(UIView*)swipingBackgoundView{
    if (!_swipingBackgoundView) {
        _swipingBackgoundView = [[UIView alloc] initWithFrame:self.view.bounds];
        _swipingBackgoundView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    }
    return _swipingBackgoundView;
}

-(NSMutableArray*)snapShotsArray{
    if (!_snapShotsArray) {
        _snapShotsArray = [NSMutableArray array];
    }
    return _snapShotsArray;
}

-(BOOL)isSwipingBack{
    if (!_isSwipingBack) {
        _isSwipingBack = NO;
    }
    return _isSwipingBack;
}

//-(UIPanGestureRecognizer*)swipePanGesture{
//    if (!_swipePanGesture) {
//        _swipePanGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(swipePanGestureHandler:)];
//    }
//    return _swipePanGesture;
//}
/**
 *  重新加载网页视图
 *
 *  @param sender
 */
- (void)SELReloadButtonPressed:(id)sender {
    
    self.webView.hidden = false;
    
//    if ([self.webView.request.URL.absoluteString length] <= 0) {
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:self.url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    [self.webView loadRequest:urlRequest];
//    }
//    else {
//       [self reloadWebView];
//    }
    NSLog(@"reloadURL:%@",self.webView.request.URL.absoluteString);
    
}

-(UIView*)noNetworkView {
    
    if (!_noNetworkView) {
        // 424 469
        _noNetworkView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 212, 234)];
        //icon_network_error 202 239
        UIImageView *tipImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_network_error"]];
        [_noNetworkView addSubview:tipImageView];
        tipImageView.frame = CGRectMake(55, 0, 101, 120);
        
        UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(6, 145, 200, 20)];
        tipLabel.font = [UIFont systemFontOfSize:14];
        tipLabel.text = @"您请求的页面失踪了......";
        tipLabel.textAlignment = NSTextAlignmentCenter;
        [_noNetworkView addSubview:tipLabel];
        
        UIButton *reloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [reloadButton setTitle:@"重新加载" forState:UIControlStateNormal];
        [reloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        reloadButton.titleLabel.font = [UIFont systemFontOfSize:15];
        reloadButton.frame = CGRectMake(0, 190, 212, 44);
        [_noNetworkView addSubview:reloadButton];
        [reloadButton addTarget:self action:@selector(SELReloadButtonPressed:)
               forControlEvents:UIControlEventTouchUpInside];
        reloadButton.backgroundColor = [UIColor colorWithRed:0.9882 green:0.549 blue:0.1725 alpha:1.0];
        reloadButton.layer.cornerRadius = 3;
        reloadButton.layer.masksToBounds = true;
        
    }
    
    return _noNetworkView;
}

-(NJKWebViewProgress*)progressProxy{
    if (!_progressProxy) {
        _progressProxy = [[NJKWebViewProgress alloc] init];
        _progressProxy.webViewProxyDelegate = (id)self;
        _progressProxy.progressDelegate = self;
    }
    return _progressProxy;
}

-(NJKWebViewProgressView*)progressView{
    if (!_progressView) {
        CGFloat progressBarHeight = 3.0f;
        CGRect navigaitonBarBounds = self.navigationController.navigationBar.bounds;
//        CGRect barFrame = CGRectMake(0, navigaitonBarBounds.size.height - progressBarHeight-0.5, navigaitonBarBounds.size.width, progressBarHeight);
        CGRect barFrame = CGRectMake(0, navigaitonBarBounds.size.height, navigaitonBarBounds.size.width, progressBarHeight);
        _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
        _progressView.progressColor = self.progressViewColor;
        _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    }
    return _progressView;
}



#pragma -mark set UIPangestureDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch locationInView:self.view].x > 40) {
        return NO;
    }
    
    if ([self.webView canGoBack]) {
        //self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        return YES;
    }
    //self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    return NO;
}

- (void)methodPanGesture:(UIPanGestureRecognizer *)pan {
    CGPoint offset = [pan translationInView:self.view];
    
    if (UIGestureRecognizerStateBegan == pan.state) {
        self.backScreenshotsImg = [self getScreenshot];
        [self setCustomShowView];
        if (self.webView.canGoBack) {
            _showView.hidden = NO;
        }
        
    } else if (UIGestureRecognizerStateChanged == pan.state) {
        if (offset.x > 0 && self.imgArray.count > 0 && self.webView.canGoBack) {
            [self setCurstomViewFrame:offset.x];
        }
        
    } else if (UIGestureRecognizerStateEnded == pan.state) {
 
        if (offset.x > 44) {
            // 移除最后一张图片,实现后退🏄
            if (self.imgArray.count > 0) {
                [self.imgArray removeLastObject];
                if ([self.webView canGoBack]) {
                    [self.webView goBack];
                    [UIView animateWithDuration:0.2 animations:^{
                        [self setCurstomViewFrame:self.view.frame.size.width];
                    } completion:^(BOOL finished) {
                        self.webView.frame = self.view.frame;
                        self->_showView.hidden = YES;
                        [self->_showView removeFromSuperview];
                    }];
                    return;
                }
            }
            _showView.hidden = YES;
        } else {
            [UIView animateWithDuration:0.2 animations:^{
                [self setCurstomViewFrame:0];
            } completion:^(BOOL finished) {
                self->_showView.hidden = YES;
            }];
        }
        /// 貌似也不需要前进功能
    }
    
}

#pragma -mark set ShowView

- (void)setCustomShowView {
    CGRect rect = [UIScreen mainScreen].bounds;
    _showView = [[UIView alloc] initWithFrame:CGRectOffset(rect, 0, 0)];
    
    /// leftView + blackView
    UIImageView *leftView = [[UIImageView alloc] initWithFrame:CGRectOffset(rect, -MOVEDISTANCE, 0)];
    leftView.contentMode = UIViewContentModeScaleAspectFit;
    if (self.imgArray.count > 0) {
        leftView.image = [self.imgArray lastObject];
    }
    leftView.tag = ShadowImgView;
    [_showView addSubview:leftView];
    
    UIView *blackView = [[UIView alloc] initWithFrame:rect];
    blackView.alpha = VIEWALPHA;
    blackView.backgroundColor = VIEWCOLOR;
    blackView.tag = BlackAlphaView;
    [_showView addSubview:blackView];
    
    _showView.layer.masksToBounds = YES;
    [self.view insertSubview:_showView belowSubview:self.webView];
}

- (void)setCurstomViewFrame:(CGFloat)x {
    if (x >= 0) {
        CGRect rect = [UIScreen mainScreen].bounds;
        CGRect left = CGRectOffset(rect, -MOVEDISTANCE, 0);
        UIView *leftView = [_showView viewWithTag:ShadowImgView];
        leftView.frame = CGRectOffset(left, (x/rect.size.width)*MOVEDISTANCE, 0);
        
        self.webView.frame = CGRectOffset(rect, x, 0);
        
        UIView *blackView = [_showView viewWithTag:BlackAlphaView];
        blackView.alpha = VIEWALPHA *(1 - x/leftView.frame.size.width);
    }
}



- (void)dealloc {
    self.webView.delegate = nil;
    NSLog(@"RxWebViewController dealloc");
}

- (UIImage *)getScreenshot {
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, [window center].x, [window center].y);
            CGContextConcatCTM(context, [window transform]);
            CGContextTranslateCTM(context,
                                  -[window bounds].size.width * [[window layer] anchorPoint].x,
                                  -[window bounds].size.height * [[window layer] anchorPoint].y);
            
            [[window layer] renderInContext:context];
            CGContextRestoreGState(context);
        }
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

@end
